using System;
using System.Collections.Generic;

namespace OpenWaves.Caching
{
    public class DictionaryCache<T> : ICache<T> where T : class
    {
        private readonly IDictionary<string, CacheEntry<T>> dictionary = new Dictionary<string, CacheEntry<T>>();

        public void InsertValue(string key, T value, DateTime absoluteExpiration)
        {
            lock(this.dictionary)
            {
                this.dictionary[key] = CacheEntry.FromValue(value, absoluteExpiration);
            }
        }

        public void EvictValue(string key)
        {
            lock (this.dictionary)
            {
                if (this.dictionary.ContainsKey(key))
                    this.dictionary.Remove(key);
            }
        }

        public T GetValue(string key)
        {
            lock (this.dictionary)
            {
                CacheEntry<T> entry;
                if (this.dictionary.TryGetValue(key, out entry) == false)
                    return null;

                if (entry.IsExpired)
                {
                    this.dictionary.Remove(key);
                    return null;
                }

                return entry.Value;
            }
        }
    }
}